package com.hx0311.core.datasource;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import com.hx0311.core.ApplicationException;

public class DataSourceManager {

	/** 数据源 */
	private static DataSource dataSource = null;

	/**
	 * 获取数据库链接,如果配置错误,或者抛出异常.
	 * 
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException {
		try {
			if (getDataSource() != null) {
				return getDataSource().getConnection();
			} else {
				throw new ApplicationException("获得数据库链接失败,数据源为空");
			}
		} catch (NamingException e) {
			throw new ApplicationException("数据源创建错误:" + e.getMessage());
		}
	}

	private static DataSource getDataSource() throws SQLException,
			NamingException {
		if (dataSource == null) {
			InitialContext ic = new InitialContext();
			dataSource = (DataSource) ic.lookup("java:comp/env/jdbc/HXBPAS");
		}
		return dataSource;
	}
}
